package com.sdnu.iosclub.qvs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdnu.iosclub.qvs.entity.*;
import com.sdnu.iosclub.qvs.entity.vo.QvsSurveyVo;
import com.sdnu.iosclub.qvs.mapper.QvsSurveyMapper;
import com.sdnu.iosclub.qvs.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdnu.iosclub.serviceutil.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wcr
 * @since 2022-09-05
 */
@Service
@CacheConfig(cacheNames = "survey")
public class QvsSurveyServiceImpl extends ServiceImpl<QvsSurveyMapper, QvsSurvey> implements QvsSurveyService {

    @Autowired
    QvsQuestionService qvsQuestionService;

    @Autowired
    private QvsOptionService qvsOptionService;

    @Autowired
    private QvsResultService qvsResultService;

    @Autowired
    private QvsTextService qvsTextService;

    @Override
    public List<QvsSurvey> getAllSurvey() {
        QueryWrapper<QvsSurvey> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("update_time");
        return this.list(wrapper);
    }

    @Override
    public Page<QvsSurvey> pageGetSurvey(long current, long size) {
        Page<QvsSurvey> page = new Page<>(current,size);
        QueryWrapper<QvsSurvey> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("update_time");
        this.page(page,wrapper);
        return page;
    }


    @Override
    public boolean addSurvey(QvsSurvey qvsSurvey) {
        return this.save(qvsSurvey);
    }

    @Override
    public boolean updateSurvey(QvsSurvey qvsSurvey) {
        return this.updateById(qvsSurvey);
    }

    @Override
    public boolean deleteSurvey(String id) {
        QueryWrapper<QvsSurvey> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        return this.remove(wrapper);
    }

    @Override
    public List<QvsSurvey> getSurveyByLike(String title) {
        QueryWrapper<QvsSurvey> wrapper = new QueryWrapper<>();
        wrapper.like("title",title);
        wrapper.orderByDesc("update_time");
        return this.list(wrapper);
    }

    @Override
    public List<QvsSurvey> getSurveyByUserId(String userId) {
        QueryWrapper<QvsSurvey> wrapper = new QueryWrapper<>();
        wrapper.eq("creator",userId);
        wrapper.orderByDesc("update_time");
        return this.list(wrapper);
    }

    @Override
    public boolean updateSurveyState(String id, Integer state) {
        QvsSurvey survey = this.getById(id);
        survey.setState(state);
        return this.updateById(survey);
    }

    @Override
    @Cacheable
    public QvsSurvey getSurveyInfoById(String id) {
        return this.baseMapper.getSurveyInfoById(id);
    }

    @Override
    public QvsSurvey getSurveyDataById(String id) {
        QvsSurvey qvsSurvey = this.baseMapper.getSurveyDataById(id);
        return qvsSurvey;
    }

    @Override
    public boolean addSurveyInfo(QvsSurvey qvsSurvey) {
        boolean surveyDone = this.save(qvsSurvey);
        //System.out.println(qvsSurvey.getId());
        boolean questionDone = true;
        for(QvsQuestion qvsQuestion : qvsSurvey.getQuestions()){
            qvsQuestion.setSurveyId(qvsSurvey.getId());
            if(!qvsQuestionService.addQuestionInfo(qvsQuestion)){
                questionDone = false;
                break;
            }
        }
        return surveyDone && questionDone;
    }

    @Override
    public List<QvsSurvey> getSurveyConditionByLike(QvsSurveyVo surveyVo) {
        QueryWrapper<QvsSurvey> wrapper=new QueryWrapper<>();

        String title=surveyVo.getTitle();
        Date startTime=surveyVo.getStartTime();
        Date endTime=surveyVo.getEndTime();
        Integer rules=surveyVo.getRules();
        Integer state=surveyVo.getState();
        Integer anon=surveyVo.getAnon();
        String creator=surveyVo.getCreator();

        if(!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        if(!(startTime ==null)){
            wrapper.ge("start_time",startTime);
        }
        if(!(endTime==null)){
            wrapper.le("end_time",endTime);
        }
        if(!(rules==null)){
            wrapper.eq("rules",rules);
        }
        if(!(state==null)){
            wrapper.eq("state",state);
        }
        if(!(anon==null)){
            wrapper.eq("anon",anon);
        }
        if(!StringUtils.isEmpty(creator)){
            wrapper.like("creator",creator);
        }
        wrapper.orderByDesc("start_time");

        return this.list(wrapper);
    }

    /**
     * 根据id逻辑删除问卷及其相关联的题目，答卷信息等
     * @param surveyId 要删除的问卷id
     * @return 返回删除状态
     */
    @Override
    @Transactional(transactionManager = "tranManager")//开启事务
    public boolean deleteSurveyAllInfo(String surveyId) {
        /**
         * 删除问卷本身的信息，问卷的题目，问卷题目的选项。问卷的所有答案
         */
        //删除问卷本身的信息
        boolean b = this.removeById(surveyId);
        //删除问卷对应的问题
        QueryWrapper<QvsQuestion> questionWrapper = new QueryWrapper<>();
        questionWrapper.eq("survey_id",surveyId);
        qvsQuestionService.remove(questionWrapper);

        //删除问卷对应的问题的选项
        QueryWrapper<QvsOption> optionWrapper = new QueryWrapper<>();
        optionWrapper.eq("survey_id",surveyId);
        qvsOptionService.remove(optionWrapper);

        //删除问卷所有的答卷内容
        QueryWrapper<QvsResult> resultWrapper = new QueryWrapper<>();
        resultWrapper.eq("survey_id",surveyId);
        qvsResultService.remove(resultWrapper);

        QueryWrapper<QvsText> textWrapper = new QueryWrapper<>();
        textWrapper.eq("survey_id",surveyId);
        qvsTextService.remove(textWrapper);

        //这里返回是否删除问卷本身的信息即可，因为添加了事务。
        return b;
    }

    /**
     * 通过id查询问卷结构，不使用缓存，直接从数据库中查，组卷过程使用
     *
     * @param surveyId 问卷id
     * @return 问卷信息
     */
    @Override
    public QvsSurvey getRealTimeSurvey(String surveyId) {
        return this.baseMapper.getSurveyInfoById(surveyId);
    }
}
